<template>
  <div class="app-container">
    <Find :OriginalFilter="{ static: true }" :formList="formList" @findClicked="findClicked" />
    <div class="flex mt10" style="width: 100%; background-color: white">
      <el-card shadow="never" :body-style="{ padding: '5px 10px 5px' }">
        <JDialog
          :tableHeader="tableHeaderJ"
          @removeOne="removeOne"
          :currentTableRow="currentTableRow"
          :unAdd="true"
          :unEdit="false"
          @confirm="confirm"
        />
        <Table
          :summaryData="summaryData"
          summary
          :tableHeader="tableHeader"
          :tableData="tableData"
          class="mt10"
          :isLoading="isLoading"
          @currentRow="currentRow"
          @selectList="selectTableList"
          selection
        />
      </el-card>
    </div>
    <el-card shadow="never" :body-style="{ padding: '5px' }">
      <PageModule :PageData="{ total, buttonS: true }" @pageSizeChange="handleSizeChange" @pageChange="handleCurrentChange" />
    </el-card>
  </div>
</template>
<script lang="ts">
import { defineComponent } from 'vue'
import 'dayjs/locale/zh-cn'
import { ElMessage, ElMessageBox } from 'element-plus'
import service from '@/utils/request'
import LoginWork from '@/utils/LoginWork'
import { formateData } from '@/plugins/mixinJ'
import router from '@/router'
import { debounce } from 'lodash'
import fileRequest from '@/utils/fileRequest'
import JMessage from '@/utils/JMessage'
export default defineComponent({
  name: 'MassProductionOrder'
})
</script>
<script lang="ts" setup>
import { i18n, Jzhcn } from '@/i18n'
import { onMounted, reactive, ref, watch } from 'vue'

// 表一模块
const formList = ref<any>([
  {
    type: 'select',
    selectValue: '',
    selectLabel: '',
    selectP: '工厂',
    selectOptions: []
  },
  {
    type: 'input',
    inputPlaceholder: '请输入型体',
    inputValue: ''
  },
  {
    type: 'input',
    inputPlaceholder: '请输入工厂指令',
    inputValue: ''
  },
  {
    type: 'date',
    dateLabel: '下单日期',
    dateValue: ''
  },
  {
    type: 'input',
    inputPlaceholder: '请输入品牌',
    inputValue: ''
  },
  {
    type: 'input',
    inputPlaceholder: '请输入鞋名',
    inputValue: ''
  },
  {
    type: 'input',
    inputPlaceholder: '请输入款号',
    inputValue: ''
  },
  {
    type: 'input',
    inputPlaceholder: '请输入季度',
    inputValue: ''
  },
  {
    type: 'input',
    inputPlaceholder: '请输入合同',
    inputValue: ''
  },
  {
    type: 'input',
    inputPlaceholder: '请输入客人IP',
    inputValue: ''
  },
  {
    type: 'input',
    inputPlaceholder: '请输入制单员',
    inputValue: ''
  },
  {
    type: 'button',
    checkboxLabel: '置空',
    bgColor: '#1890FF'
  },
  {
    type: 'button',
    checkboxLabel: '结案'
  },
  {
    type: 'button',
    checkboxLabel: '取消结案'
  },
  {
    type: 'button',
    checkboxLabel: '量产订单导入'
  },
  {
    type: 'button',
    checkboxLabel: '删除打勾记录',
    bgColor: '#FF0000'
  },
  {
    type: 'button',
    checkboxLabel: '导出'
  }
])

const tableHeader = ref([
  {
    label: '工厂',
    prop: 'vendorAbbr'
  },
  {
    label: '品牌',
    prop: 'brand'
  },
  {
    width: '120px',
    label: '鞋名',
    prop: 'styleName'
  },
  {
    width: '120px',
    label: '款号',
    prop: 'custStyle'
  },
  {
    width: '120px',
    label: '工厂指令号',
    prop: 'factoryLotNo'
  },
  {
    label: '订单数',
    prop: 'orderQty'
  },
  {
    width: '120px',
    label: '下单日期',
    prop: 'customOrderDate'
  },
  {
    width: '120px',
    label: '交期',
    prop: 'deliveryDate'
  },
  {
    type: 'svg',
    label: '结案',
    prop: 'complete'
  },
  {
    label: '预计生产',
    prop: 'predicProdDate'
  },
  {
    label: '客人单价',
    prop: 'custPrice'
  },
  {
    label: '客人币种',
    prop: 'custCur'
  },
  {
    label: '工厂单价',
    prop: 'factoryPrice'
  },
  {
    label: '工厂币种',
    prop: 'factoryCur'
  },
  {
    type: 'svg',
    label: '冲刀试做',
    prop: 'cutSample'
  },
  {
    type: 'svg',
    label: '产前样',
    prop: 'antenatalSample'
  },
  {
    type: 'svg',
    label: '试穿样',
    prop: 'tryOnSample'
  },
  {
    type: 'svg',
    label: '测试样',
    prop: 'testSample'
  },
  {
    type: 'svg',
    label: 'CFS样',
    prop: 'cfsSample'
  },
  {
    type: 'svg',
    label: '原材料',
    prop: 'rawMaterial'
  },
  {
    type: 'svg',
    label: '鞋带',
    prop: 'shoelace'
  },
  {
    label: '冲裁',
    prop: 'cutQty'
  },
  {
    label: '工艺',
    prop: 'craftQty'
  },
  {
    label: '配套',
    prop: 'matchQty'
  },
  {
    label: '针车',
    prop: 'stitchQty'
  },
  {
    label: '大底',
    prop: 'outSoleQty'
  },
  {
    label: '鞋垫',
    prop: 'insoleQty'
  },
  {
    label: '成型',
    prop: 'finishQty'
  },
  {
    width: '120px',
    label: '制单日期',
    prop: 'createDate'
  },
  {
    label: '制单人',
    prop: 'createUserName'
  },
  {
    width: '120px',
    label: '型体',
    prop: 'styleNo'
  },
  {
    label: '颜色',
    prop: 'styleColor'
  },
  {
    label: '颜色代码',
    prop: 'colorCode'
  },
  {
    label: '季度',
    prop: 'season'
  },
  {
    label: '订单类型',
    prop: 'orderType'
  },
  {
    label: '合同号',
    prop: 'factoryContractNo'
  },
  {
    label: '客人PI号',
    prop: 'customPiNo'
  },
  {
    label: '备注',
    prop: 'remark'
  }
])
const currentTableRow = ref({}) as any

const tableHeaderJ = ref([
  {
    label: '客人单价',
    prop: 'custPrice'
  },
  {
    type: 'selectJ',
    label: '客人币种',
    prop: 'custCur',
    options: [
      {
        value: 'RMB',
        label: 'RMB'
      },
      {
        value: 'USD',
        label: 'USD'
      }
    ]
  },
  {
    label: '工厂单价',
    prop: 'factoryPrice'
  },
  {
    type: 'selectJ',
    label: '工厂币种',
    prop: 'factoryCur',
    options: [
      {
        value: 'RMB',
        label: 'RMB'
      },
      {
        value: 'USD',
        label: 'USD'
      }
    ]
  },
  {
    label: '订单数',
    prop: 'orderQty'
  }
])
// 表一按钮
const findClicked = async (content: string) => {
  if (content === '置空') {
    formList.value.forEach((item: any) => {
      item.inputValue = ''
      item.selectValue = ''
      item.dateValue = ''
    })
  }
  if (content === '结案') {
    let res = (await LoginWork.post<any, any>('/subcontract/static/complete', currentTableRow.value)) as any
    if (res.code === 200) {
      JMessage.success('结案成功')
      getTableList()
    } else {
      JMessage.error(res.message)
    }
  }
  if (content === '取消结案') {
    let res = (await LoginWork.post<any, any>('/subcontract/static/cancel/complete', currentTableRow.value)) as any
    if (res.code === 200) {
      JMessage.success('取消结案成功')
      getTableList()
    } else {
      JMessage.error(res.message)
    }
  }
  if (content === '导出') {
    if (tableData.value.length === 0) {
      JMessage.error('暂无数据')
      return
    }
    let formData = new FormData()
    formData.append('vendorNo', formList.value[0].selectValue.split('  ')[1] || '')
    formData.append('styleNo', formList.value[1].inputValue)
    formData.append('factoryLotNo', formList.value[2].inputValue)
    formData.append('endTime', formList.value[3].dateValue[1] || '')
    formData.append('beginTime', formList.value[3].dateValue[0] || '')
    formData.append('brand', formList.value[4].inputValue)
    formData.append('styleName', formList.value[5].inputValue)
    formData.append('custName', formList.value[6].inputValue)
    formData.append('season', formList.value[7].inputValue)
    formData.append('factoryContractNo', formList.value[8].inputValue)
    formData.append('customPiNo', formList.value[9].inputValue)
    formData.append('createUserName', formList.value[10].inputValue)
    formData.append('pageNum', String(currentPage.value))
    formData.append('pageSize', String(pageSize.value))
    const res = (await fileRequest.post(`/subcontract/static/download/oem`, formData)) as any
    const link = document.createElement('a') // 利用a标签自定义下载文件名
    let blob = new Blob([res.data]) // 创建Blob对象，设置文件类型
    link.style.display = 'none'
    //设置连接
    link.href = window.URL.createObjectURL(blob)
    const FileName = decodeURI(res.headers['content-disposition'].split(`utf-8''`)[1])
    link.download = FileName //自定义文件名字
    document.body.appendChild(link)
    //模拟点击事件
    link.click()
    document.body.removeChild(link)
  }
  if (content === '量产订单导入') {
    upload(2)
  }
  if (content === '删除打勾记录') {
    const res = (await service.post('/subcontract/static/deleteList', selectedLists.value)) as any
    if (res.code === 200) {
      JMessage.success('删除成功')
      getTableList()
    } else {
      JMessage.error(res.message)
    }
  }
}
const upload = async (type: number = 1) => {
  const fileType = ['xls', 'xlsx']
  const inputFile = document.createElement('input')
  const maxFileSizeMb = 2
  const maxFilesSizeBytes = maxFileSizeMb * 1024 * 1024
  inputFile.type = 'file'
  inputFile.style.display = 'none'
  document.body.appendChild(inputFile)
  inputFile.addEventListener('change', async function () {
    const files = inputFile.files as any // 获取文件数组
    const file = files[0] // 获取第一个文件对象
    const fileExtension = file.name.split('.').pop()
    if (!fileType.includes(fileExtension as any)) {
      JMessage.warning('上传的文件格式只能是 xls, xlsx')
      document.body.removeChild(inputFile)
      return false
    }
    if (file.size > maxFilesSizeBytes) {
      JMessage.warning('文件大小不能超过2MB!!!')
      document.body.removeChild(inputFile)
      return
    }
    const formData = new FormData() as any
    formData.append('file', file) // 添加文件对象及文件名
    let result = {} as any
    if (type === 1) {
      result = (await LoginWork.post('/pcOrder/uploadPcOrderHeadTemp', formData)) as any
    } else if (type === 2) {
      result = (await LoginWork.post('/pcOrder/uploadPcBatchOrder', formData)) as any
    }
    if (result.code === 200) {
      JMessage.success(result.message)
      getTableList()
    } else {
      JMessage.error(result.message)
    }
  })
  inputFile.click()
}
const tableData = ref([])
const isLoading = ref(true)
// 总计
interface summaryDataType {
  index: number
  num: number | undefined
}
const summaryData = ref<summaryDataType[]>([
  {
    index: 5,
    num: 0
  },
  {
    index: 10,
    num: 0
  },
  {
    index: 12,
    num: 0
  },
  {
    index: 21,
    num: 0
  },
  {
    index: 22,
    num: 0
  },
  {
    index: 23,
    num: 0
  },
  {
    index: 24,
    num: 0
  },
  {
    index: 25,
    num: 0
  },
  {
    index: 26,
    num: 0
  },
  {
    index: 27,
    num: 0
  }
])
// 分页器
const currentPage = ref(1)
const pageSize = ref(40)
const total = ref(0)
const handleSizeChange = (val: number) => {
  pageSize.value = val
  getTableList()
}
const handleCurrentChange = (val: number) => {
  currentPage.value = val
  getTableList()
}
// 获取表数据
const getTableList = debounce(async () => {
  isLoading.value = true
  let formData = new FormData()
  formData.append('styleNo', formList.value[1].inputValue)
  formData.append('factoryLotNo', formList.value[2].inputValue)
  formData.append('params[endTime]', formList.value[3].dateValue[1] || '')
  formData.append('params[beginTime]', formList.value[3].dateValue[0] || '')
  formData.append('brand', formList.value[4].inputValue)
  formData.append('styleName', formList.value[5].inputValue)
  formData.append('custName', formList.value[6].inputValue)
  formData.append('season', formList.value[7].inputValue)
  formData.append('factoryContractNo', formList.value[8].inputValue)
  formData.append('customPiNo', formList.value[9].inputValue)
  formData.append('createUserName', formList.value[10].inputValue)
  formData.append('vendorAbbr', formList.value[0].selectValue ? formList.value[0].selectValue.split('  ')[0] : '')
  formData.append('vendorNo', formList.value[0].selectValue ? formList.value[0].selectValue.split('  ')[1] : '')

  formData.append('pageNum', String(currentPage.value))
  formData.append('pageSize', String(pageSize.value))
  let tableDataList = await service.post<any, any>('/subcontract/static/list', formData)
  isLoading.value = false
  tableData.value = tableDataList.list
  total.value = tableDataList.total
  currentRow()
  summaryData.value[0].num = tableDataList.summary.ORDER_QTY
  summaryData.value[1].num = tableDataList.summary.CUST_PRICE
  summaryData.value[2].num = tableDataList.summary.FACTORY_PRICE
  summaryData.value[3].num = tableDataList.summary.CUT_QTY
  summaryData.value[4].num = tableDataList.summary.CRAFT_QTY
  summaryData.value[5].num = tableDataList.summary.MATCH_QTY
  summaryData.value[6].num = tableDataList.summary.STITCH_QTY
  summaryData.value[7].num = tableDataList.summary.OUT_SOLE_QTY
  summaryData.value[8].num = tableDataList.summary.INSOLE_QTY
  summaryData.value[9].num = tableDataList.summary.FINISH_QTY
}, 500)
onMounted(() => {
  getTableList()
})
watch(
  () =>
    formList.value.map((item: any) => {
      item.selectValue, item.inputValue, item.dateValue, item.checked
    }),
  () => {
    getTableList()
  }
)
// 点击表给另一张表传数据
const currentRow = async (row: any = tableData.value[0] ? tableData.value[0] : {}) => {
  currentTableRow.value = row
}
const selectedLists = ref([]) as any
const selectTableList = (selectedList: any) => {
  selectedLists.value = selectedList
}
// Dialog确认添加/修改按钮
const confirm = async (obj: any, dialogVisible: any, title: any) => {
  // 向服务器发送请求
  if (title === '修改') {
    const res = (await LoginWork.post(`/subcontract/static/updatePrice`, {
      ...obj,
      factoryCur: obj.factoryCur.value ? obj.factoryCur.value : obj.factoryCur,
      custCur: obj.custCur.value ? obj.custCur.value : obj.custCur
    })) as any
    // 判断请求是否成功
    if (res.code === 200) {
      JMessage.success(res.message)
    } else {
      JMessage.error(res.message)
    }
  }
  // 关闭弹出框
  dialogVisible.value = false
  // 重新获取表格数据
  getTableList()
}
// 删除
const removeOne = async () => {
  let res = (await LoginWork.post<any, any>('/subcontract/static/delete', currentTableRow.value)) as any
  if (res.code === 200) {
    JMessage.success('订单删除成功')
    getTableList()
  } else {
    JMessage.error(res.message)
  }
  getTableList()
}

const getSelectList = async () => {
  const res = await LoginWork.post('/subcontract/static/oem/combo')
  formList.value[0].selectOptions = res.data.map((item: any) => {
    return {
      optionKey: item.vendorAbbr,
      optionValue: `${item.vendorAbbr}  ${item.vendorNo}`,
      optionLabel: item.vendorAbbr
    }
  })
}
onMounted(() => {
  getSelectList()
})
</script>
